package com.itheima.reggie.controller;

import com.itheima.reggie.commen.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.filepath}")
    private String BasePath;
    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();

        //先判断文件夹是否存在
        File basePath = new File(BasePath);
        if (!basePath.exists()){
            basePath.mkdirs();
        }

        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        //对文件进行转存
        try {
            file.transferTo(new File(BasePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }

    //文件下载，对上传完的图片进行回显
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //进行io流读取
        byte[] bytes = new byte[1024];
        int lenght;
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(BasePath + name));
            //获取响应流
            ServletOutputStream outputStream = response.getOutputStream();
            while ((lenght = fileInputStream.read(bytes))!=-1){
               outputStream.write(bytes,0,lenght);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
